#include "stdafx.h"
#include "MessageLoop.h"

CxMessageLoop::CxMessageLoop()
    : m_pState(NULL)
    , m_bQuitAll(false)
{}

CxMessageLoop::~CxMessageLoop()
{}

HRESULT CxMessageLoop::FinalConstruct()
{
    return S_OK;
}

void CxMessageLoop::FinalRelease()
{
}

HRESULT CxMessageLoop::Run()
{
    RunState state;
    state.nRunDepth = m_pState ? m_pState->nRunDepth + 1 : 1;

    RunState* pPreviousState = m_pState;
    m_pState = &state;

    _do_run_loop();

    m_pState = pPreviousState;

    if (m_bQuitAll && m_pState && m_pState->nRunDepth > 0)
    {
        ::PostQuitMessage(0);
    }

    return S_OK;
}

HRESULT CxMessageLoop::Quit()
{
    ::PostQuitMessage(0);
    return S_OK;;
}

HRESULT CxMessageLoop::QuitAll()
{
    ::PostQuitMessage(0);
    m_bQuitAll = true;
    return S_OK;
}

HRESULT CxMessageLoop::InitService()
{
    return S_OK;
}

HRESULT CxMessageLoop::UninitService()
{
    return S_OK;
}

void CxMessageLoop::_do_run_loop()
{
    MSG msg = {0};

    while ( ::GetMessage(&msg, NULL, 0, 0) )
    {
        ::TranslateMessage(&msg);
        ::DispatchMessage(&msg);
    }
}